from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File
from src.schemas.user import (
    UserLoginRequest,
    LoginResponse,
    UpdateUserRequest,
    UserInfo,
    RefreshTokenRequest,
    RefreshTokenResponse,
    RefreshTokenApiResponse
)
from src.schemas import SuccessResponse, ErrorResponse
from src.services import UserService
from src.services.refresh_token_service import RefreshTokenService
from src.utils.auth import get_current_user
from src.models import User
from src.utils.logger import app_logger as logger

router = APIRouter(prefix="/user")


@router.post(
    "/login",
    response_model=SuccessResponse[LoginResponse],
    summary="微信登录",
    description="使用微信授权码进行登录，返回用户信息和访问令牌"
)
async def login(request: UserLoginRequest):
    """微信登录"""
    try:
        result = await UserService.login_with_wechat(request.code)
        return SuccessResponse(
            data=result,
            message="登录成功"
        )
    except Exception as e:
        logger.error(f"微信登录失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )


@router.get(
    "/info",
    response_model=SuccessResponse[UserInfo],
    summary="获取用户信息",
    description="获取当前登录用户的详细信息"
)
async def get_user_info(current_user: User = Depends(get_current_user)):
    """获取用户信息"""
    try:
        result = await UserService.get_user_profile(current_user.id)
        return SuccessResponse(
            data=result,
            message="获取用户信息成功"
        )
    except Exception as e:
        logger.error(f"获取用户信息失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )


@router.put(
    "/info",
    response_model=SuccessResponse[UserInfo],
    summary="更新用户信息",
    description="更新用户的昵称和头像信息"
)
async def update_user_info(
    request: UpdateUserRequest,
    current_user: User = Depends(get_current_user)
):
    """更新用户信息"""
    try:
        result = await UserService.update_user_profile(current_user.id, request)
        return SuccessResponse(
            data=result,
            message="更新用户信息成功"
        )
    except Exception as e:
        logger.error(f"更新用户信息失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )


@router.post(
    "/refresh",
    response_model=RefreshTokenApiResponse,
    summary="刷新访问令牌",
    description="使用refresh token获取新的access token"
)
async def refresh_token(request: RefreshTokenRequest):
    """刷新访问令牌"""
    try:
        result = await RefreshTokenService.refresh_access_token(request.refresh_token)
        if not result:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="无效的refresh token或已过期"
            )
        
        response_data = RefreshTokenResponse(
            access_token=result["access_token"],
            token_type=result["token_type"],
            expires_in=result["expires_in"]
        )
        
        return SuccessResponse(
            data=response_data,
            message="令牌刷新成功"
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"刷新令牌失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )


@router.post(
    "/logout",
    response_model=SuccessResponse[dict],
    summary="用户登出",
    description="撤销用户的refresh token，实现安全登出"
)
async def logout(
    request: RefreshTokenRequest,
    current_user: User = Depends(get_current_user)
):
    """用户登出"""
    try:
        # 撤销指定的refresh token
        success = await RefreshTokenService.revoke_refresh_token(request.refresh_token)
        
        if success:
            logger.info(f"用户 {current_user.id} 登出成功")
            return SuccessResponse(
                data={"logged_out": True},
                message="登出成功"
            )
        else:
            return SuccessResponse(
                data={"logged_out": False},
                message="登出失败，token可能已失效"
            )
    except Exception as e:
        logger.error(f"用户登出失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )





@router.post(
    "/avatar",
    response_model=SuccessResponse[UserInfo],
    summary="上传用户头像",
    description="上传用户头像到OSS并更新用户信息"
)
async def upload_avatar(
    avatar: UploadFile = File(..., description="头像文件"),
    current_user: User = Depends(get_current_user)
):
    """上传用户头像"""
    try:
        result = await UserService.upload_avatar(current_user.id, avatar)
        return SuccessResponse(
            data=result,
            message="头像上传成功"
        )
    except Exception as e:
        logger.error(f"头像上传失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )